import time

from django.db.models import Q
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from models import *
from Puer.constant import constant
import json
import traceback
import datetime


# 首页
def index(request):
    try:
        get_user_id = request.GET.get('userId')
        is_user_phone = False
        is_vip =False
        # 轮播图
        index_swiper_list = Indexswiper.objects.all()
        data1 = []
        user = Users.objects.filter(userid=get_user_id)
        if user:
            is_user_phone = True if user[0].userphone else False
            is_vip = True if user[0].uservip else False
        for swiper in index_swiper_list:
            data1.append("%s%s" % (constant.FILE_ADDRESS, swiper.image))
        # 活动邀约
        activity_list = Activity.objects.filter(status=constant.NOW)
        activity_pic = []
        for activity in activity_list:
            activity_pic.append("%s%s" % (constant.FILE_ADDRESS, activity.picture))
        # 所有的商品
        # products = Product.objects.filter(status=constant.ON)
        data3 = []
        data2 = []
        data4 = []
        flash_product = Flashsale.objects.all()
        for flash in flash_product:
            data2.append(flash.productid)
        open_book = Openbooking.objects.all()
        for book in open_book:
            data4.append(book.productid)
        search_product_result = Product.objects.filter(status=constant.PRODUCT_STATE).filter(
            ~Q(productid__in=data2)).filter(~Q(productid__in=data4))
        for product in search_product_result:
            dic = {
                'product_id': product.productid,  # 商品id
                'price': "%.2f" % float(product.price),  # 价格
                'product_name': product.name,  # 商品名
                'product_thumbnail': '%s%s' % (constant.FILE_ADDRESS, product.thumbnail)  # 缩略图
            }
            data3.append(dic)
        data = {
            'index_swiper': data1,  # 轮播图
            'activity_pic': activity_pic,  # 邀约图
            'products': data3,  # 所有的商品
            'is_vip': is_vip,
            'is_user_phone': is_user_phone  # 用户是否注册手机号

        }
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# ----------------------------------------PC----------------------------------------

def pc_index(request):
    # 每天0点的时间戳
    t = time.localtime(time.time())
    time1 = time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00', t), '%Y-%m-%d %H:%M:%S'))
    # 这周的第一天和下周的第一天
    now = datetime.datetime.now()
    this_week_start = (now - datetime.timedelta(days=now.weekday())).strftime('%Y-%m-%d 0:0:0')
    time2 = datetime.datetime.strptime(this_week_start, "%Y-%m-%d %H:%M:%S")
    t1 = time.mktime(time2.timetuple())
    next_week_start = (now - datetime.timedelta(days=now.weekday() - 7)).strftime('%Y-%m-%d 0:0:0')
    time2 = datetime.datetime.strptime(next_week_start, "%Y-%m-%d %H:%M:%S")
    t2 = time.mktime(time2.timetuple())
    try:
        order_list = Payorders.objects.filter(paykind=constant.BUY)
        # 昨日收入
        yesterday_earning = 0
        # 昨日订单数
        yesterday_order = 0
        # 本周收入
        all_earn = 0
        weak_order = []
        add_product = 0
        all_stock = 0
        all_standard_num = 0
        for order in order_list:
            d = order.date.strftime("%Y-%m-%d %H:%M:%S")
            date = time.mktime(time.strptime(d, "%Y-%m-%d %H:%M:%S"))

            if (date > time1 - 24 * 60 * 60) and (date < time1):
                yesterday_earning += order.money * 100
                yesterday_order += 1
            if (date > t1) and (date < t2):
                all_earn += order.money * 100
                weak_order.append(order)
                # 昨日入库
                add_product = 0
                # 总库存量
                all_stock = 0
                product_list = Product.objects.filter(status=constant.PROCESSED)
                for product in product_list:
                    all_stock += product.stock
                    d = product.onlinetime.strftime("%Y-%m-%d %H:%M:%S")
                    date = time.mktime(time.strptime(d, "%Y-%m-%d %H:%M:%S"))
                    if (date > time1 - 24 * 60 * 60) and (date < time1):
                        add_product += 1
                # 总品类量
                all_standard_num = 0
                all_product_list = Productstandard.objects.all()
                for product in all_product_list:
                    all_standard_num += product.stock
        data = {
            # 昨日收入
            'yesterday_earning': yesterday_earning,
            # 昨日订单数
            'yesterday_order': yesterday_order,
            # 本周收入
            'all_earn': all_earn,
            # 昨日入库
            'add_product': add_product,
            # 总库存量
            'all_stock': all_stock,
            # 总品类量
            'all_standard_num': all_standard_num,
            # 总订单量
            'all_order_num': len(weak_order)

        }

        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
